package com.xxxx.controller;


import com.alibaba.fastjson.JSONObject;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URL;

@Controller
public class ExtracionController {


    @GetMapping("goExtraction")
    public String goExtraction(){
        return "user/imgextraction";
    }

    @PostMapping("ExtractionImg")
    @ResponseBody
    public String ExtractionImg(@Param("imgName") String imgName, HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();

        String dir = System.getProperty("user.dir");

        String imgPath = dir + "/" + imgName;

        File file = new File(imgPath);

        if (file != null && file.isFile()) {

            //创建实例
            ITesseract iTesseract = new Tesseract();

            try {
                //无需设置路径，默认读取根目录

                URL property = this.getClass().getClassLoader().getResource("");
                String path = property.getPath();

                System.out.println("路径"+"------"+path+"/static/tessdata/");
             //  iTesseract.setDatapath(path+"static/tessdata/");

               //本地路径
                iTesseract.setDatapath(dir+"\\tessdata\\");

                //设置语言包
              iTesseract.setLanguage("chi_sim+eng");
                String content = iTesseract.doOCR(file);
                jsonObject.put("code", "0");
                jsonObject.put("message", content);
            } catch (TesseractException e) {
                jsonObject.put("code", "1");
                jsonObject.put("message", e);
                e.printStackTrace();
            }
        } else {
            jsonObject.put("code", "1");
            jsonObject.put("message", "文件不存在");
        }

        return jsonObject.toJSONString();
    }
}
